import ArticleOperate from "./components/articleOperate";
import ArticleContent from "./components/articleContent";
import Ai from "@/components/ai/ai";
import AuthorInfo from "@/components/authorInfo";
import Recommend from "@/components/recommend";
import Comment from "@/components/comment";
import RightFixed from "@/components/rightFixed/rightFixed";
import RecommendToYou from "@/components/recommendToYou";
import { useParams } from "react-router-dom";
import { message } from "antd";
import {
  GetArticleCommentListApi,
  PostCommentApi,
  PostLikeApi,
} from "@/http/api/comment";
import { GetArticleAndAuthorDetailApi } from "@/http/api/article";
import {
  PostWithAiDialogueApi,
  GetDialogueListApi,
  DeleteUserDialogueListApi,
} from "@/http/api/ai";
import articleDetailLess from "./index.module.less";
import { useEffect, useState, useRef } from "react";
type ChatMessage = {
  content: string;
  role: string;
  ChatTime: string;
  IsStop: number;
  IsSatisfied: number;
};
function ArticleDetail() {
  const { id } = useParams();
  const [ArticleInfo, setArticleInfo] = useState();
  const [AuthorMessage, setAuthorMessage]: any = useState();
  const [commentList, setCommentList] = useState([]);
  const [LengthList, setLengthList] = useState([]);
  const [ShowCommentList, setShowCommentList] = useState([]);
  const [ShowAll, setShowAll] = useState(false);
  const CommentRef: any = useRef(null);
  const [showAi, setShowAi] = useState(false);
  const [value, setValue] = useState("");
  const [done, setDone] = useState(false);
  const doneRef = useRef(true);
  const [isUserScrolled, setIsUserScrolled] = useState(false);
  const [showLoading, setShowLoading] = useState(false);
  const [comFullScreen, setComFullScreen] = useState(false);
  const cancelRequest = useRef(false);
  const [beforeChatTime, setBeforeChatTime] = useState("");
  const [abortController, setAbortController]: any = useState(null);
  const [chatList, setChatList] = useState<ChatMessage[]>([]);
  const chatListRef: any = useRef(chatList);
  const GetArticleAndAuthorDetails = async () => {
    const params = {
      ArticleId: Number(id),
    };
    const res: any = await GetArticleAndAuthorDetailApi(params);
    console.log("获取文章作者详情", res);
    if (res.status === 0) {
      setArticleInfo(res.ArticleInfo);
      setAuthorMessage(res.AuthorInfo);
    }
  };

  const GetDialogueList = async (time: string = "") => {
    const params = {
      BeforeChatTime: time,
      PageSize: 20,
      PageNum: 1,
    };
    const res: any = await GetDialogueListApi(params);
    console.log("获取到聊天列表", res, time);
    if (res.status === 0) {
      if (time) {
        setBeforeChatTime(time);
        setChatList((prevChatList) => [...res.AiDialogueList, ...prevChatList]);
      } else {
        setChatList(() => res.AiDialogueList);
      }
      console.log("获取列表结束");
    }
  };
  useEffect(() => {
    chatListRef.current = chatList;
    console.log("更新后的聊天列表", chatList, chatListRef.current);
  }, [chatList]); // chatList 改变时会触发这个 effect

  const GetCommentList = async () => {
    const params = {
      ArticleId: Number(id),
    };
    const res: any = await GetArticleCommentListApi(params);
    console.log("获取评论列表", res);
    if (res.status === 0) {
      //处理
      const CommentList: any = [];
      res.CommentList.forEach((item: any) => {
        CommentList.push({
          ...item,
          InputShow: false,
          InputContent: "",
        });
      });
      const LengthList = CommentList.splice(0, 3);
      setCommentList(CommentList);
      setLengthList(LengthList);
      setShowCommentList(LengthList);
      /* if (CommentList.length > 0) {
        setcommentPlaceholder("平等表达，友善交流");
      } else {
        setcommentPlaceholder("抢首评，友善交流");
      } */
    }
  };

  const showAllCommentList = () => {
    setShowCommentList(commentList);
    setShowAll(true);
  };

  const onsetCommentList = (updatedCommentList: any) => {
    setCommentList(updatedCommentList);
  };

  const FusendCommentMethods = async (commentInfo: any) => {
    console.log(3333, commentInfo);
    const params = {
      CommentContent: commentInfo.CommentContent,
      ArticleId: Number(id),
      FatherCommentId: commentInfo.FatherCommentId,
      AtUserId: commentInfo.AtUserId,
    };
    const res = await PostCommentApi(params);
    console.log("评论发送结果", res);
    if (res.status === 0) {
      message.success("评论成功!");
      console.log(333333333, CommentRef);
      CommentRef.current?.ClearFuInput();
      GetCommentList();
      /* if(commentInfo.FatherCommentId) */
    }
  };

  const LikeComment = async (item: any) => {
    console.log(333, item);
    const params = {
      CommentId: item.CommentId,
    };
    const res = await PostLikeApi(params);
    console.log("点赞结果", res);
    if (res.status === 0) {
      GetCommentList();
    }
  };
  const AiExplanation = async (text: string) => {
    console.log("父组件接收到值", text);
    if (!doneRef.current) return;
    await GetDialogueList();
    sendUserMsg("请解释一下：" + text);
    setShowAi(true);
    setIsUserScrolled(false);
  };
  const closeAi = () => {
    setShowAi(false);
  };

  const clearAi = async () => {
    const res = await DeleteUserDialogueListApi();
    if (res.status === 0) {
      GetDialogueList();
    }
  };

  const showFuAi = () => {
    GetDialogueList();
    setShowAi(true);
  };

  const fullScreen = () => {
    setComFullScreen((prev) => !prev);
  };
  const loadMore = () => {
    console.log("触发向上加载", chatListRef.current);
    GetDialogueList(chatListRef.current[0].ChatTime);
  };

  const stopStream = () => {
    doneRef.current = true;
    if (abortController) {
      abortController.abort(); // 取消请求
      doneRef.current = true;
    }
  };

  const sendUserMsg = async (text: string) => {
    if (!text.trim()) return;
    doneRef.current = false;
    setChatList((prevChatList) => {
      return [
        ...prevChatList,
        {
          content: text,
          role: "user",
          ChatTime: "",
          IsSatisfied: 0,
          IsStop: 0,
        },
      ];
    });
    const content = {
      Usercontent: text,
      accessToken: localStorage.getItem("accessToken"),
      refreshToken: localStorage.getItem("refreshToken"),
    };
    setValue("");
    setShowLoading(true);
    try {
      /* if (abortController) {
        abortController.abort(); // 取消之前的请求
      } */
      // 创建一个新的 AbortController
      const controller = new AbortController();
      setAbortController(controller); // 保存控制器以便之后使用
      const responseStream: any = await fetch(
        "http://127.0.0.1:6789/api/WithAiDialogue",
        {
          method: "POST", // 请求方法
          headers: {
            "Content-Type": "application/json", // 根据需要设置其他头部
            Authorization: `Bearer ${localStorage.getItem("accessToken")}`, // 携带 token
          },
          body: JSON.stringify(content), // 将复杂的参数对象转换为 JSON 字符串
          signal: controller.signal, // 将取消信号传递给请求
        }
      );
      if (!responseStream.ok) {
        throw new Error("Network response was not ok");
      }

      const reader = responseStream.body.getReader();
      const decoder = new TextDecoder();
      let done = false;
      let result = "";

      // 持续读取流数据，直到完成
      while (!done) {
        const { value, done: readerDone } = await reader.read();
        done = readerDone;
        doneRef.current = done;
        result += decoder.decode(value, { stream: true });
        if (result) {
          setShowLoading(false);
        }
        setChatList((prevChatList): any => {
          console.log("prevChatList", prevChatList);
          const lastMessage = prevChatList[prevChatList.length - 1];
          if (result) {
            if (lastMessage && lastMessage.role === "assistant") {
              // 如果最后一条消息是 AI 的，更新内容
              return [
                ...prevChatList.slice(0, -1),
                {
                  content: result,
                  role: "assistant",
                  ChatTime: "",
                  IsStop: 0,
                  IsSatisfied: 0,
                },
              ];
            } else {
              // 否则，添加新的 AI 消息
              return [
                ...prevChatList,
                {
                  content: result,
                  role: "assistant",
                  ChatTime: "",
                  IsStop: 0,
                  IsSatisfied: 0,
                },
              ];
            }
          }
        });
        console.log("doneRef", doneRef.current);
      }
    } catch (error: any) {
      if (error.name === "AbortError") {
        console.log("请求已被取消");
        setChatList((prevChatList) => {
          // 如果 prevChatList 为空，直接返回
          if (prevChatList.length === 0) return prevChatList;
          // 创建一个新的数组，避免直接修改原数组
          const newChatList = prevChatList.map((item, index) => {
            // 如果是最后一个对象，修改 IsStop 为 1
            if (index === prevChatList.length - 1) {
              return { ...item, IsStop: 1 }; // 使用扩展运算符创建新对象
            }
            // 其他对象保持不变
            return item;
          });

          return newChatList;
        });
      } else {
        console.error("请求发生错误", error);
      }
    } finally {
      setShowLoading(false);
    }
  };

  useEffect(() => {
    GetArticleAndAuthorDetails();
    GetCommentList();
    GetDialogueList();
  }, []);
  return (
    <>
      <div className={articleDetailLess.ArticleDetail_content}>
        <div className="left_operate">
          <ArticleOperate AuthorMessage={AuthorMessage} />
        </div>
        <div className="center_article_content">
          <div className="article_content">
            <ArticleContent
              ArticleInfo={ArticleInfo}
              AuthorMessage={AuthorMessage}
              sendAiExplanation={AiExplanation}
            />
          </div>
          <div className="comment_content">
            <Comment
              ref={CommentRef}
              key={1}
              AuthorMessage={AuthorMessage}
              ArticleInfo={ArticleInfo}
              commentList={ShowCommentList}
              commentLength={commentList}
              ShowAll={ShowAll}
              showAllCommentList={showAllCommentList}
              onsetCommentList={onsetCommentList}
              FusendCommentMethods={FusendCommentMethods}
              LikeComment={LikeComment}
            />
          </div>
          <div className="recommendToyou">
            <RecommendToYou />
          </div>
        </div>
        <div className="right_other_message">
          <div className="author_info">
            <AuthorInfo
              AuthorMessage={AuthorMessage}
              ArticleInfo={ArticleInfo}
            />
          </div>
          <div className="recommend">
            <Recommend />
          </div>
        </div>
        <div className="rightBottomFixed">
          <RightFixed showFuAi={showFuAi} />
        </div>
        {showAi && (
          <div
            className={[
              comFullScreen ? "showAiContentScreen" : "showAiContent",
            ].join(" ")}
          >
            <Ai
              value={value}
              showLoading={showLoading}
              setValue={(v: string) => setValue(v)}
              closeFuAi={closeAi}
              clearFuAi={clearAi}
              fullFuScreen={fullScreen}
              sendUserFuMsg={sendUserMsg}
              stopFuStream={stopStream}
              setIsFuUserScrolled={(v: boolean) => setIsUserScrolled(v)}
              loadFuMore={loadMore}
              chatList={chatList}
              beforeChatTime={beforeChatTime}
              isUserScrolled={isUserScrolled}
              done={doneRef.current}
            />
          </div>
        )}
      </div>
    </>
  );
}

export default ArticleDetail;
